﻿using Castle.DynamicProxy;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Search.IBLL;
using CNKI.TPI.Web.Search.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.SessionState;
using System.Web.UI;
using System.Xml;

namespace CNKI.TPI.Web.UI.Controllers.Search
{
    [SessionState(SessionStateBehavior.ReadOnly)]
    public class DocResourceController : BaseController
    {
        INaviService naviService = null;
        IUserService userService=null;
        ISearchService searchService=null;
        IFileService fileService = null;
        public DocResourceController(INaviService naviService, IUserService userService, ISearchService searchService, IFileService fileService)
        {
            this.naviService = generator.CreateInterfaceProxyWithTarget<INaviService>(naviService, new IInterceptor[] { new LogInterceptor() });
            this.userService = generator.CreateInterfaceProxyWithTarget<IUserService>(userService, new IInterceptor[] { new LogInterceptor() });
            this.searchService = generator.CreateInterfaceProxyWithTarget<ISearchService>(searchService, new IInterceptor[] { new LogInterceptor() });
            this.fileService = generator.CreateInterfaceProxyWithTarget<IFileService>(fileService, new IInterceptor[] { new LogInterceptor() });
        }
        //
        // GET: /Database/

        public ActionResult Index()
        {
            IList<SYS_CMS_DATABASE_CLS_NODE> databaseList = naviService.GetDataBaseList(PermissionOption.None);
            ViewBag.DatabaseList = databaseList;
            //ViewBag.MediaType = 0;//文档标识
            return View("DocResource");
        }
        public ActionResult DocView(string dbName, int resourceId,int recordId, int dbId, int downType)
        {
            ViewBag.dbId = dbId;
            //ViewBag.DownloadCAJ = "javascript:alert('附件不存在')";
            //ViewBag.DownloadPDF = "javascript:alert('附件不存在')";
            //int fileId = 0;
            //IList<METADATA_FILE> list = searchService.GetFile(recordId, dbName);
            //if (list != null)
            //{
            //    foreach (METADATA_FILE file in list)
            //    {
            //        if (file.FORMAT == "CAJ" || file.FORMAT == "PDF")
            //        {
            //            ViewBag.Download = ResourceHelper.GetFileDownloadURL(dbId, file.SYSID);
            //            fileId = file.SYSID;
            //            break;
            //        }
            //    }
            //}
            int fileId = resourceId;
            ViewBag.Download = ResourceHelper.GetFileDownloadURL(dbId, fileId,recordId,downType);
            ViewBag.DownType = downType;
            ViewBag.dbName = dbName;
            ViewBag.RecordID=recordId;
            
            if (fileId != 0)
            {
                ViewBag.AttachId = fileId;
            }
            else
            {
                ViewBag.AttachId = 0;
            }

            string filePath = fileService.GetDigitalFile(dbId, ViewBag.AttachId);
            if ((!string.IsNullOrEmpty(filePath)) && ResourceHelper.CheckFileExist(filePath))
            {
                ViewBag.IsFileExsit = true;
            }
            else
            {
                ViewBag.IsFileExsit = false;
            }
            ViewBag.OnlineViewUrl = ResourceHelper.GetOnlineViewUrl(dbId, fileId, downType, dbName, recordId);
            return View();
        }

        public void FileRead(int dbId,int fileId,int downType,string dbName,int recordID)
        {
            string filePath = fileService.GetDigitalFile(dbId, fileId);

            string strFileInfo = Request.ServerVariables["HTTP_REQUEST_ACTION"];
            if (strFileInfo != null && strFileInfo == "FileInfo")
            {
                InitFileInfo(filePath);
                return ;
            }

            string strAcceptRange = Request.ServerVariables["HTTP_ACCEPT_RANGE"];
            if (strAcceptRange == null)
            {
                Response.StatusCode = 500;
                return;
            }
            int n = strAcceptRange.IndexOf("bytes=");
            if (n == -1)
            {
                return ;
            }

            strAcceptRange = strAcceptRange.Remove(0, n + 6);
            strAcceptRange = strAcceptRange.Trim();
            n = strAcceptRange.IndexOf("-");

            long nStartFilePos = 0;
            string strFilePos = strAcceptRange.Substring(0, n);
            if (strFilePos != null && strFilePos.Length > 0)
                nStartFilePos = long.Parse(strFilePos);

            FileInfo info = new FileInfo(filePath);

            long nEndFilePos = info.Length;
            strFilePos = strAcceptRange.Substring(n + 1, strAcceptRange.Length - n - 1);
            if (strFilePos != null && strFilePos.Length > 0)
                nEndFilePos = long.Parse(strFilePos);
            if (nEndFilePos > info.Length)
                nEndFilePos = info.Length;
            if (filePath.Substring(0, 1) == "\\")
            {
                string sDomin = filePath.Substring(1, filePath.Length - 1);
                sDomin = sDomin.Substring(0, sDomin.IndexOf('\\'));
                {
                    using (FileStream fs = System.IO.File.Open(filePath, FileMode.Open))
                    {
                        byte[] bytes = new byte[nEndFilePos - nStartFilePos];
                        fs.Seek(nStartFilePos, SeekOrigin.Begin);
                        fs.Read(bytes, 0, (int)(nEndFilePos - nStartFilePos));
                        Response.BinaryWrite(bytes);
                    }
                }
            }
            else
            {
                Response.WriteFile(filePath, nStartFilePos, nEndFilePos - nStartFilePos);
            }

            //LogOpr.Download(dbId,dbName,recordID.ToString(),fileId.ToString(),downType);//记录下载
        }
        private void InitFileInfo(string filePath)
        {
            string strFileInfo = Request.ServerVariables["HTTP_REQUEST_ACTION"];

            if (strFileInfo != null && strFileInfo == "FileInfo")
            {
                FileInfo info = new FileInfo(filePath);

                //MemoryStream o1 = new MemoryStream();
                //XmlTextWriter docInfo = new XmlTextWriter(o1, Encoding.UTF8);
                //docInfo.WriteStartDocument();
                //docInfo.WriteStartElement("root");
                //docInfo.WriteStartElement("docInfo");
                //docInfo.WriteStartElement("display");
                //docInfo.WriteStartElement("locate");
                //docInfo.WriteString("10");
                //docInfo.WriteEndElement();
                //docInfo.WriteStartElement("pageMode");
                //docInfo.WriteString("0");
                //docInfo.WriteEndElement();
                //docInfo.WriteEndElement();
                //docInfo.WriteEndElement();
                //docInfo.WriteEndDocument();
                //docInfo.Close();
                //o1.Close();

                XmlTextWriter w = new XmlTextWriter(Response.OutputStream, Encoding.GetEncoding(936));
                w.Formatting = Formatting.Indented;
                w.WriteStartDocument();
                w.WriteStartElement("root"); 
                w.WriteStartElement("document");
                w.WriteStartElement("length");
                w.WriteString(info.Length.ToString());
                w.WriteEndElement();
                w.WriteStartElement("filename");
                w.WriteString(filePath.Substring(filePath.LastIndexOf('\\') + 1));
                w.WriteEndElement();
                w.WriteEndElement();

                w.WriteStartElement("server");
                w.WriteStartElement("cache");
                w.WriteStartElement("type");

                string strValidPeriod = System.Configuration.ConfigurationManager.AppSettings["validPeriod"];
                if (strValidPeriod == null || strValidPeriod == "")
                    strValidPeriod = "temp";
                w.WriteAttributeString("validPeriod", strValidPeriod);

                string strCacheType = System.Configuration.ConfigurationManager.AppSettings["cache-type"];
                if (strCacheType == null || strCacheType == "")
                    strCacheType = "mem";
                if (strCacheType == "file")
                {
                    string strCacheSize = System.Configuration.ConfigurationManager.AppSettings["cache-size"];
                    if (strCacheSize != null && strCacheSize != "")
                    {
                        long nCacheSize = Int32.Parse(strCacheSize);
                        if (info.Length < nCacheSize)
                            strCacheType = "mem";
                    }
                }
                w.WriteString(strCacheType);
                w.WriteEndElement();

                string strPreparse = System.Configuration.ConfigurationManager.AppSettings["preparse"];
                if (strPreparse == null || strPreparse == "")
                    strPreparse = "1";
                w.WriteStartElement("preparse");
                w.WriteString(strPreparse);
                w.WriteEndElement();
                w.WriteEndElement();

                w.WriteStartElement("cluster");
                w.WriteStartElement("threads");
                string strThreads = System.Configuration.ConfigurationManager.AppSettings["threads"];
                if (strThreads == null || strThreads == "")
                    strThreads = "5";
                w.WriteString(strThreads);
                w.WriteEndElement();
                w.WriteStartElement("url");
                w.WriteAttributeString("pri", "10");
                w.WriteCData(Request.Url.AbsoluteUri);
                w.WriteEndElement();
                w.WriteStartElement("url");
                w.WriteAttributeString("pri", "9");
                w.WriteCData(Request.Url.AbsoluteUri);
                w.WriteEndElement();
                w.WriteEndElement();
                w.WriteEndElement();
                w.WriteEndDocument();

                w.Close();
            }
        }
    }
}
